﻿using FreeSql;
using ManaSky.Apollo;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ManaSky.DBCore.Context
{
    /// <summary>
    /// FreeSql封装类
    /// </summary>
    public class FreeSqlContext
    {
        private FreeSqlContext()
        {
            db = new FreeSqlBuilder()
               .UseConnectionString(DataType.MySql, ConnectionString)
               .UseAutoSyncStructure(false) //自动同步实体结构到数据库
               .Build(); //请务必定义成 Singleton 单例模式
            DbAop();
        }
        private static FreeSqlContext dbContext { get; set; } = new FreeSqlContext();
        /// <summary>
        /// Db对象
        /// </summary>
        private IFreeSql db { get; set; }

        /// <summary>
        /// 获取单例的FreeSql db对象
        /// </summary>
        /// <returns></returns>
        public static IFreeSql GetInstance()
        {
            if (dbContext == null)
                dbContext = new FreeSqlContext();
            return dbContext.db;
        }
        /// <summary>
        /// 主库连接字符串
        /// </summary>
        private static string ConnectionString
        {
            get
            {
                string strConn = AppsettingsHelper.GetConfig("ConnectionStrings:mysql");
                return strConn;
            }
        }
        private void DbAop()
        {
            //记录访问数库的日志
            db.Aop.CurdBefore += (s, e) => {
                string result = e.Sql + "\r\n" +
                    e.DbParms.ToDictionary(it => it.ParameterName, it => it.Value);
                //日志存储路径
                
                string fileDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "App_Data", "Sql");
                //日志文件名
                string logName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                //日志存储
                string fileName = Path.Combine(fileDirectory, logName);
                try
                {
                    if (!Directory.Exists(fileDirectory))
                        Directory.CreateDirectory(fileDirectory);
                    if (!File.Exists(fileName))
                    {
                        StreamWriter sw;
                        sw = File.CreateText(fileName);
                        sw.Close();
                    }
                    File.AppendAllText(fileName, Environment.NewLine + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   " + result);
                }
                catch
                {
                    //
                }
            };

            //实现插入/更新时统一处理某些值，比如某属性的雪花算法值、创建时间值、甚至是业务值。
            db.Aop.AuditValue += (s, e) => {
                //if (e.Column.CsType == typeof(long)
                //    && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) != null
                //    && e.Value?.ToString() == 0)
                //    e.Value = new Snowflake().GetId();
                //if (e.Property.Name == "UptDtt") e.Value = DateTime.Now;
                //if (e.Property.Name == "CreaDtt") e.Value = DateTime.Now;
            };
        }
    }
}
